{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入数据包\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from mlxtend.preprocessing import TransactionEncoder\n",
    "from mlxtend.frequent_patterns import apriori,association_rules,fpgrowth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读取表格数据\n",
    "# 产品表,日期表,客户表,订单表\n",
    "df_product = pd.read_csv(\"..\\\\data\\\\product.csv\", encoding='gbk')\n",
    "df_date = pd.read_csv(\"..\\\\data\\\\date.csv\", encoding='gbk')\n",
    "df_customer = pd.read_csv('..\\\\data\\\\customer.csv', encoding='gbk')\n",
    "df_order = pd.read_csv('..\\\\data\\order.csv', encoding='gbk')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# 查看表格数据\n",
    "df_order['订单日期'] = pd.to_datetime(df_order['订单日期'])\n",
    "print(df_order.head(5))\n",
    "print(df_customer.columns,'\\n',\n",
    "df_date.columns,'\\n',\n",
    "df_order.columns,'\\n',\n",
    "df_product.info)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 查看主要工作表数据 各维度信息、数据是否缺失、数据格式\n",
    "df_order.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# 查看数据描述性统计\n",
    "df_order.describe()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 对订单进行聚类，制表：同一客户同一天购买的所有商品，相同商品需要去重\n",
    "df_group = df_order.groupby(['客户ID','订单日期',])['产品名称'].unique()\n",
    "df_group\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "order_list = []\n",
    "for i in df_group.values:\n",
    "    order_list.append(list(i))\n",
    "order_list[0:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "TE = TransactionEncoder() # 构造模型\n",
    "data = TE.fit_transform(order_list) #将原始数据转换成布尔值\n",
    "df = pd.DataFrame(data, columns=TE.columns_)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 设定最小支持度为0.01\n",
    "items = apriori(df,min_support=0.01,use_colnames=True)\n",
    "items.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 查看长度大于2的频繁项集\n",
    "items[items['itemsets'].apply(lambda x: len(x)>1)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 根据最小置信度在频繁项集中 产生强关联规则，设定最小信度为2\n",
    "rules = association_rules(items, min_threshold=0.2)\n",
    "rules[rules['lift']>1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 通过下列代码提取results中的关联规则\n",
    "for i,j in rules.iterrows(): # 遍历二维表中的每一行\n",
    "    x = j['antecedents']   #关联规则的前件\n",
    "    y = j['consequents']   #关联规则的后件\n",
    "    x = ','.join([item for item in x]) #链接前件中的元素\n",
    "    y = ','.join([item for item in y])  #链接后件中的元素\n",
    "    print(x + '--->' + y)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FGgrowth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frequent_items = fpgrowth(df, min_support=0.01, use_colnames=True, max_len=None, verbose=0).sort_values(by='support', ascending=False)\n",
    "frequent_items"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ass_rule = association_rules(frequent_items, metric='confidence', min_threshold=0.2, support_only=False).sort_values(by=['lift','support'], ascending=False)\n",
    "ass_rule"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ass_rule[ass_rule['lift']>1][['antecedents','consequents','support','confidence','lift']] # 只看Lift大于1的结果"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "7b4b4feff2f24a0f0a34464dbe537a36fda679851528fb8735cb41fa49dffb2d"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
